<template>
  <el-card class="dr-task" body-class="task-card" shadow="never">
    <template #header>
      视频任务
      <!-- TODO @fan：看看，怎么优化下这个样子哈。 -->
      <el-button @click="handleViewPublic">视频作品</el-button>
    </template>
    <!-- 视频详情列表 -->
    <div class="task-video-list" ref="videoListRef">
      <VideoCard
        v-for="video in videoList"
        :key="video.id"
        :detail="video"
        @on-btn-click="handleVideoButtonClick"
      />
    </div>
    <div class="task-video-pagination">
      <Pagination
        :total="pageTotal"
        v-model:page="queryParams.pageNo"
        v-model:limit="queryParams.pageSize"
        @pagination="getVideoList"
      />
    </div>
  </el-card>

  <!-- 视频详情详情 -->
  <VideoDetail
    :show="isShowVideoDetail"
    :id="showVideoDetailId"
    @handleDetailClose="handleDetailClose"
    @handle-drawer-close="handleDetailClose"
  />

  <el-dialog
    title="视频详情查看"
    v-model="showDialog"
    append-to-body
    destroy-on-close
    style="width: 400px;"
  >
    <div>
      <video
        ref="videoPlayer"
        class="w-full w-full"
        :src="videoUrl"
        :poster="thumbnailUrl"
        :autoplay="false"
        controls
      ></video>
    </div>

    <template #footer>
      <el-button @click="showDialog = false">取 消</el-button>
    </template>
  </el-dialog>

</template>
<script setup lang="ts">
import {
  VideoApi,
  VideoVO,
} from '@/api/ai/video'
import VideoDetail from './VideoDetail.vue'
import VideoCard from './VideoCard.vue'
import { ElLoading, LoadingOptionsResolved } from 'element-plus'
import { AiVideoStatusEnum } from '@/views/ai/utils/constants'
import download from '@/utils/download'

const message = useMessage() // 消息弹窗
const router = useRouter() // 路由

// 视频详情分页相关的参数
let queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
})
const pageTotal = ref<number>(0) // page size
const videoList = ref<VideoVO[]>([]) // video 列表
const videoListLoadingInstance = ref<any>() // video 列表是否正在加载中
const videoListRef = ref<any>() // ref
// 视频详情轮询相关的参数（正在生成中的）
const inProgressVideoMap = ref<{}>({}) // 监听的 video 映射，一般是生成中（需要轮询），key 为 video 编号，value 为 video
const inProgressTimer = ref<any>() // 生成中的 video 定时器，轮询生成进展
// 视频详情详情相关的参数
const isShowVideoDetail = ref<boolean>(false) // 视频详情详情是否展示
const showVideoDetailId = ref<number>(0) // 视频详情详情的视频详情编号

const showDialog = ref(false)
const videoUrl = ref<string>();
const thumbnailUrl = ref<string>();
/** 处理查看绘图作品 */
const handleViewPublic = () => {
  router.push({
    name: 'AiVideoSquare'
  })
}

/** 查看视频详情的详情  */
const handleDetailOpen = async () => {
  isShowVideoDetail.value = true
}

/** 关闭视频详情的详情  */
const handleDetailClose = async () => {
  isShowVideoDetail.value = false
}

/** 获得 video 视频详情列表 */
const getVideoList = async () => {
  try {
    // 1. 加载视频详情列表
    videoListLoadingInstance.value = ElLoading.service({
      target: videoListRef.value,
      text: '加载中...'
    } as LoadingOptionsResolved)
    //所属平台
    queryParams = Object.assign(queryParams, {

    });
    const { list, total } = await VideoApi.getVideoPage(queryParams)
    videoList.value = list
    pageTotal.value = total

    // 2. 计算需要轮询的视频详情
    const newWatVideos = {}
    videoList.value.forEach((item) => {
      if (item.status === AiVideoStatusEnum.IN_PROGRESS) {
        newWatVideos[item.id] = item
      }
    })
    inProgressVideoMap.value = newWatVideos
  } finally {
    // 关闭正在“加载中”的 Loading
    if (videoListLoadingInstance.value) {
      videoListLoadingInstance.value.close()
      videoListLoadingInstance.value = null
    }
  }
}

/** 轮询生成中的 video 列表 */
const refreshWatchVideos = async () => {
  const videoIds = Object.keys(inProgressVideoMap.value).map(Number)
  if (videoIds.length == 0) {
    return
  }
  const list = (await VideoApi.getVideoListMyByIds(videoIds)) as VideoVO[]
  const newWatchVideos = {}
  list.forEach((video) => {
    if (video.status === AiVideoStatusEnum.IN_PROGRESS) {
      newWatchVideos[video.id] = video
    } else {
      const index = videoList.value.findIndex((oldVideo) => video.id === oldVideo.id)
      if (index >= 0) {
        // 更新 videoList
        videoList.value[index] = video
      }
    }
  })
  inProgressVideoMap.value = newWatchVideos
}

/** 视频详情的点击事件 */
const handleVideoButtonClick = async (type: string, videoDetail: VideoVO) => {
  // 详情
  if (type === 'more') {
    showVideoDetailId.value = videoDetail.id
    await handleDetailOpen()
    return
  }
  // 删除
  if (type === 'delete') {
    await message.confirm(`是否删除视频?`)
    await VideoApi.deleteVideo(videoDetail.id)
    await getVideoList()
    message.success('删除成功!')
    return
  }
  // 下载
  if (type === 'download') {
    const url = videoDetail.videoUrl;
    // 使用URL对象解析网址（适用于绝对URL）
    const parsedUrl = new URL(url);
    // 获取文件名，剥离路径
    const filename = parsedUrl.pathname.split('/').pop(); // 得到 'file.txt'
    if(filename){
      await download.downloadUrl(url, filename);
    }
    return
  }
  // 重新生成
  if (type === 'regeneration') {
    await emits('onRegeneration', videoDetail)
    return
  }
  //预览模型
  if(type === 'open'){
    const detail = await VideoApi.getVideo(videoDetail.id)
    if(detail.videoUrl && detail.thumbnailUrl){
      videoUrl.value = detail.videoUrl;
      thumbnailUrl.value = detail.thumbnailUrl;
    }
    showDialog.value = true
    return;
  }
}

defineExpose({ getVideoList }) // 暴露组件方法

const emits = defineEmits(['onRegeneration', 'onOpen', 'onTexture',
  'onRefine', 'onAnimationRig', 'onAnimationRigRetarget'])

/** 组件挂在的时候 */
onMounted(async () => {
  // 获取 video 列表
  await getVideoList()
  // 自动刷新 video 列表
  inProgressTimer.value = setInterval(async () => {
    await refreshWatchVideos()
  }, 1000 * 3)
})

/** 组件取消挂在的时候 */
onUnmounted(async () => {
  if (inProgressTimer.value) {
    clearInterval(inProgressTimer.value)
  }
})
</script>
<style lang="scss">
.dr-task {
  width: 100%;
  height: 100%;
}
.task-card {
  margin: 0;
  padding: 0;
  height: 100%;
  position: relative;
}

.task-video-list {
  position: relative;
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  align-content: flex-start;
  height: 100%;
  overflow: auto;
  padding: 20px 20px 140px;
  box-sizing: border-box; /* 确保内边距不会增加高度 */

  > div {
    margin-right: 20px;
    margin-bottom: 20px;
  }
  > div:last-of-type {
    //margin-bottom: 100px;
  }
}

.task-video-pagination {
  position: absolute;
  bottom: 60px;
  height: 50px;
  line-height: 90px;
  width: 100%;
  z-index: 999;
  background-color: #ffffff;
  display: flex;
  flex-direction: row;
  justify-content: center;
  align-items: center;
}
</style>
